package interview.huawei.tjt.training.shuzu;

import java.util.Scanner;

/**
 * 二分查找
 *
 * 给定一个 n 个元素有序的（升序）整型数组 nums 和一个目标值 target  ，写一个函数搜索 nums 中的 target，如果目标值存在返回下标，否则返回 -1。
 */
public class BinarySearch {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNextLine()) {
            String[] strings = sc.nextLine().split(",");
            int[] nums = new int[strings.length];
            for (int i = 0; i < strings.length; i ++) {
                if (!strings[i].equals("") && strings[i] != null) {
                    nums[i] = Integer.parseInt(String.valueOf(strings[i]));
                }
            }
            int target = sc.nextInt();
            int left = 0;
            int right = nums.length - 1;

            if (target < nums[0] || target > nums[nums.length - 1]) {
                System.out.println("Error");
            }
            while (left <= right) {
                int middle = left + (right - left)/2;
                if (nums[middle] == target) {
                    System.out.println(middle);
                    break;
                } else if (nums[middle] < target) {
                    left = middle + 1;
                } else if (nums[middle] > target) {
                    right = middle - 1;
                }
            }
        }
    }

}
